package com.netty.netty.test;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 描述：TODO
 *
 * @author: zhubb
 * @Date:2020/6/4
 * @Package:com.netty.netty.test
 * @version:1.0
 */

public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    Logger log = LoggerFactory.getLogger(this.getClass());


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) throws Exception {

        log.info("收到的消息:{}",msg.text());
        sendAllMessage(msg.text());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx)throws Exception{
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx)throws Exception{
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    }


    private void sendAllMessage(String msg) {
        MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(msg));
    }
}
